package chat.network.tcp;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.*;
import android.os.Process;
import android.util.Log;

import com.whu.administrator.ws.MyApplication;

import model.OwnUser;

/**
 * 与推送服务在同一主进程中
 * Created by Administrator on 2016/3/8.
 */
public class PushControlReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (PushService.netWorkAvailable(context)) {
            String action = intent.getStringExtra(PushService.SERVICE_ACTION);
            PushService.sendMsgToPush(action);
        }

        if (intent.getStringExtra(PushService.SERVICE_ACTION)!=null && intent.getStringExtra(PushService.SERVICE_ACTION).equals(PushService.ACTION_DESTORY))
        {
            String action = intent.getStringExtra(PushService.SERVICE_ACTION);
            PushService.sendMsgToPush(action);
        }

        // 网络变化
        if (intent.getAction() != null && intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            this.onDevicesNetworkChanged(context,info);
        }
    }


    // 网络发生变化
    private void onDevicesNetworkChanged(Context context,NetworkInfo info) {

        OwnUser ownUser = MyApplication.getOwnUser();
        if (ownUser == null)return;
        if (info == null) {
            Log.i("网络不可用","关闭定时闹铃");
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, TimeReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.cancel(pendingIntent);
        }
        else
        {
            Log.i("网络可用", "打开定时闹铃");
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, TimeReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);
            // 重置定时闹铃
            TimeCheck.share().init();
        }

    }
}
